package day1.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@WebServlet("/jsp/day1/cookie/*")
public class C extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("content-type", "text/html;charset=utf8");
        String contextPath=req.getContextPath();
        String urlPath=req.getRequestURI().toString();
        String servletPath=req.getServletPath();
        System.out.println("ser:"+servletPath+",con:"+contextPath+",url:"+urlPath);
        if(urlPath.contains("add")){
            addC(req,resp);
        }else if(urlPath.contains("select")){
            selectC(req,resp);
        }else if(urlPath.contains("delete")){
            deleteC(req,resp);
        }else if(urlPath.contains("modify")){
            modifyC(resp);
        }

        resp.getWriter().write("访问成功！");
    }

    private void modifyC(HttpServletResponse resp) {
        Cookie c=new Cookie("username","this is username");
        resp.addCookie(c);
    }

    private void deleteC(HttpServletRequest req, HttpServletResponse resp) {
        Cookie c=new Cookie("phone","");
        c.setMaxAge(0);
        resp.addCookie(c);
    }

    private void selectC(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("服务器端从客户的cookie:");
        Cookie[]arr=req.getCookies();
        for(Cookie c:arr){
            System.out.println(c.getName()+":"+c.getValue());
        }

    }

    private void addC(HttpServletRequest req, HttpServletResponse resp) {
        Cookie c=new Cookie("phone","139");
        resp.addCookie(c);//默认的cookie路径为：/jsp/day1/cookie

        c=new Cookie("username","hello");
        c.setPath("/");
        resp.addCookie(c);

    }
}
